

package com.googlecode.flac4j.format.frame.sub;


import com.googlecode.jinahya.io.BitInput;
import com.googlecode.jinahya.io.BitOutput;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;


/**
 *
 * @author Jin Kwon <jinahya at gmail.com>
 */
@XmlType(propOrder = {"values"})
public class VERBATIM extends AbstractSubData {


    /**
     * Creates a new instance.
     */
    public VERBATIM() {
        super(0x01, 0);
    }


    @Override
    public void read(final BitInput input) throws IOException {

        final int bitsPerSample = getFrameHeader().getSampleSize();
        final int blockSize = getFrameHeader().getBlockSize();
        values.clear();
        for (int i = 0; i < blockSize; i++) {
            values.add(input.readUnsignedInt(bitsPerSample));
        }
    }


    @Override
    public void write(final BitOutput output) throws IOException {

        final int bitsPerSample = getFrameHeader().getSampleSize();
        final int blockSize = getFrameHeader().getBlockSize();
        if (values.size() != blockSize) {
            throw new IllegalStateException(
                "values.size(" + values.size() + ") != blockSize("
                + blockSize + ")");
        }
        for (int value : values) {
            output.writeUnsignedInt(bitsPerSample, value);
        }
    }


    // ------------------------------------------------------------------ values
    /**
     * Clears values.
     */
    public void clearSamples() {
        values.clear();
    }


    /**
     * Returns the number of values added so far.
     *
     * @return the number of values
     */
    public int getValueCount() {
        return values.size();
    }


    /**
     * Adds given <code>value</code> to the list.
     *
     * @param value value to add
     */
    public void addValue(final int value) {

        final int bitsPerSample = getFrameHeader().getSampleSize();

        if (value >> bitsPerSample != 0) {
            throw new IllegalArgumentException(
                "value(" + value + ") >> bitsPerSample(" + bitsPerSample
                + ") != 0)");
        }

        values.add(value);
    }


    @XmlElement(name = "value")
    @XmlElementWrapper(required = true)
    private final List<Integer> values = new ArrayList<Integer>();


}

